package com.ylbh.modules.yyt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ylbh.common.pojo.goods.dto.GoodsDTO;
import com.ylbh.common.pojo.goods.dto.GoodsImgDTO;
import com.ylbh.common.pojo.goods.dto.SpecPropertyDTO;
import com.ylbh.common.utils.*;
import com.ylbh.modules.accessory.GoodsInventoryDetails;
import com.ylbh.modules.goods.service.GoodsSpecService;
import com.ylbh.modules.goods.service.ShoppingGoodsService;
import com.ylbh.modules.yyt.entity.Sku;
import com.ylbh.modules.yyt.entity.SkuInventory;
import com.ylbh.modules.yyt.entity.SkuPrice;
import com.ylbh.modules.yyt.entity.SpuDetail;
import net.sf.json.JSONArray;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;

/**
 * @author: czx
 * @date: 2019/12/24 15:17
 */
@RestController
public class Test {

    @Autowired
    private GoodsSpecService goodsSpecService;

    @Autowired
    private ShoppingGoodsService shoppingGoodsService;

    public static String appKey = "yd8f7d0b54efeaa5f8";

    public static String appSecret = "850ebca5a67a49e19c3dbe23e9631347.";

    public static String baseUrl = "http://pre-openapi.380star.com";


    @GetMapping()
    public CommonResult addYYT() {
        System.out.println(System.currentTimeMillis());
        Map<String, String> map1 = new HashMap<>();
        map1.put("pageIndex", "10");
        map1.put("pageSize", "10");
        // 查询出商品的SpuId列表
        String spuIdList = HttpUtils.sendPost(baseUrl + "/goods/getSpuIdList", setBaseParams(map1));
        JSONObject spuIds = JSON.parseObject(spuIdList);
        org.json.JSONObject spuIdData = new org.json.JSONObject(spuIds);
        Object spuId = spuIdData.get("data");
        org.json.JSONObject idList = new org.json.JSONObject(spuId.toString());
        Object ids = idList.get("spuIdList");
        List<String> id = FastJsonUtil.toList(ids.toString(), String.class);
        System.out.println(""+id.toString());
        String spuIdJoin = String.join(",", id);

        // 根据spuId查询spu详情
        Map<String, String> map2 = new HashMap<>();
        map2.put("spuIds", spuIdJoin);
        String spuDetailList = HttpUtils.sendPost(baseUrl + "/goods/getSpuDetail", setBaseParams(map2));
        JSONObject spuData = JSON.parseObject(spuDetailList);
        org.json.JSONObject spuList = new org.json.JSONObject(spuData);
        Object spuDetail = spuList.get("data");
        // 商品基本信息List
        List<SpuDetail> spuDetails = FastJsonUtil.toList(spuDetail.toString(), SpuDetail.class);
        if (null != spuDetails && spuDetails.size() > 0) {
            for (int i = 0; i < spuDetails.size(); i++) {
                GoodsDTO dto = new GoodsDTO();
                SpuDetail yytDetails = spuDetails.get(i);

                // 只要商品状态是0（上架）
                if ("0".equals(yytDetails.getStatus())) {
                    dto.setGoodsName(yytDetails.getName());
                    dto.setSeoDescription(yytDetails.getName());
                    dto.setSeoKeywords(yytDetails.getName());
                    dto.setGoodsBrief(yytDetails.getName());
                    dto.setExpressTransFee(new BigDecimal("0"));
                    dto.setGiveIntegralType(1);
                    dto.setGoodsStatus(1);
                    dto.setGoodsTransfee(0);
                    dto.setPriceType("2");
                    dto.setGoodsDetails(yytDetails.getDetailInfo());
                    if ("0".equals(yytDetails.getCrossBorder())) {
                        dto.setTradeType(2);
                        dto.setOverseasGoods(0);
                    } else {
                        dto.setTradeType(5);
                        dto.setOverseasGoods(1);
                    }
                    dto.setGoodsSaleNum((int) (Math.random() * (500 - 200 + 1) + 200));
                    dto.setSupplyChainType(2);
                    ArrayList<GoodsImgDTO> imgList = new ArrayList<>();
                    for (int b = 0; b < yytDetails.getDetailImgUrlList().size(); b++) {
                        GoodsImgDTO img = new GoodsImgDTO();
                        img.setUrl("https://image.yilianbaihui.cn/consumer/" + TaoBaoUtils.uploadFile(yytDetails.getDetailImgUrlList().get(b), "", "upload/store/33307/" + DateHelper.getDate()));
                        if (b == 0) {
                            imgList.add(img);
                            dto.setMainImg(imgList);
                        } else {
                            imgList.add(img);
                        }
                    }
                    dto.setRollingImg(imgList);


                    // 根据spuId查询sku列表
                    Map<String, String> map3 = new HashMap<>();
                    map3.put("spuId", spuDetails.get(i).getSpuId());
                    String skuListDetailBySpuId = HttpUtils.sendPost(baseUrl + "/goods/getSkuListDetailBySpuId", setBaseParams(map3));
                    JSONObject skuListDetailBySpuIdJson = JSON.parseObject(skuListDetailBySpuId);
                    org.json.JSONObject skuList = new org.json.JSONObject(skuListDetailBySpuIdJson);
                    Object code = skuList.get("code");
                    if ("0".equals(code.toString())) {
                        Object skuData = skuList.get("data");
                        List<Sku> skus = FastJsonUtil.toList(skuData.toString(), Sku.class);

                        // 商品规格集合
                        List<GoodsInventoryDetails> jsonList = new ArrayList<>();

                        if (null != skus && skus.size() > 0) {
                            for (int j = 0; j < skus.size(); j++) {
                                // 这里需要去判断规格属性数据库是否存在
                                GoodsInventoryDetails gidtj = new GoodsInventoryDetails();
                                for (int l = 0; l < skus.get(j).getSkuPropertyList().size(); l++) {
                                    // 根据规格的属性和值查询值id

                                    // 先去shopping_goodsspecification表中查询是否有这个值
                                    List<Integer> goodsSpecId = goodsSpecService.getGoodsSpecificationByName(skus.get(j).getSkuPropertyList().get(l).getName());
                                    if (null != goodsSpecId && goodsSpecId.size() > 0) {
                                        List<Integer> specId = goodsSpecService.getIsExistenceByNameAndVal(goodsSpecId.get(0).toString(), skus.get(j).getSkuPropertyList().get(l).getVal());
                                        if (null != specId && specId.size() > 0) {
                                            if (!StringUtils.isEmpty(gidtj.getId())) {
                                                gidtj.setId(gidtj.getId() + specId.get(0) + "_");
                                            } else {
                                                gidtj.setId(specId.get(0) + "_");
                                            }
                                        } else {
                                            // 则要去增加规格属性下的值
                                            SpecPropertyDTO spdto = new SpecPropertyDTO();
                                            spdto.setSpecId(goodsSpecId.get(0));
                                            spdto.setName(skus.get(j).getSkuPropertyList().get(l).getVal());
                                            goodsSpecService.addSpec(spdto, new Date());
                                            if (null == spdto.getId()) {
                                                // 如果插入都没有返回id就去查
                                                spdto = goodsSpecService.selectSpecIdByName(spdto);
                                                if (null == spdto.getId()) {
                                                    return Ref.error("不存在");
                                                }
                                            }
                                            if (!StringUtils.isEmpty(gidtj.getId())) {
                                                gidtj.setId(gidtj.getId() + spdto.getId() + "_");
                                            } else {
                                                gidtj.setId(spdto.getId() + "_");
                                            }
                                        }
                                    } else {
                                        // 先去增加规格属性并返回id，然后根据返回id去增加规格值
                                        SpecPropertyDTO spdto = new SpecPropertyDTO();
                                        spdto.setName(skus.get(j).getSkuPropertyList().get(l).getName());
                                        goodsSpecService.addGoodsSpecification(spdto);
                                        if (null != spdto.getId()) {
                                            SpecPropertyDTO sdto = new SpecPropertyDTO();
                                            sdto.setSpecId(goodsSpecId.get(0));
                                            sdto.setName(skus.get(j).getSkuPropertyList().get(l).getVal());
                                            goodsSpecService.addSpec(sdto, new Date());
                                            if (null == sdto.getId()) {
                                                // 如果插入都没有返回id就去查
                                                sdto = goodsSpecService.selectSpecIdByName(sdto);
                                                if (null == sdto.getId()) {
                                                    return Ref.error("不存在2");
                                                }
                                            } else {
                                                if (!StringUtils.isEmpty(gidtj.getId())) {
                                                    gidtj.setId(gidtj.getId() + sdto.getId() + "_");
                                                } else {
                                                    gidtj.setId(sdto.getId() + "_");
                                                }
                                            }
                                        }
                                    }

                                }
                                gidtj.setImgPath(dto.getMainImg().get(0).getUrl());

                                // 查询sku的库存
                                Map<String, String> map4 = new HashMap<>();
                                map4.put("codes", skus.get(j).getCode());
                                map4.put("skuIds", skus.get(j).getSkuId());
                                String findSkuInventory = HttpUtils.sendPost(baseUrl + "/goods/findSkuInventory", setBaseParams(map4));
                                JSONObject findSkuInventoryJson = JSON.parseObject(findSkuInventory);
                                org.json.JSONObject findSkuInventoryData = new org.json.JSONObject(findSkuInventoryJson);
                                Object inventory = findSkuInventoryData.get("data");
                                org.json.JSONObject inventoryData = new org.json.JSONObject(inventory.toString());
                                Object skuInvList = inventoryData.get("skuInvList");
                                List<SkuInventory> skuInventory = FastJsonUtil.toList(skuInvList.toString(), SkuInventory.class);
                                if (null != skuInventory && skuInventory.size() > 0)
                                    gidtj.setCount(skuInventory.get(0).getInventoryCount());


                                // 查询sku的价格
                                Map<String, String> map5 = new HashMap<>();
                                map5.put("skuIds", skus.get(j).getSkuId());
                                map5.put("codes", skus.get(j).getCode());
                                String findSkuSalePrice = HttpUtils.sendPost(baseUrl + "/goods/findSkuSalePrice", setBaseParams(map5));
                                JSONObject findSkuSalePriceJson = JSON.parseObject(findSkuSalePrice);
                                org.json.JSONObject findSkuSalePriceData = new org.json.JSONObject(findSkuSalePriceJson);
                                Object price = findSkuSalePriceData.get("data");
                                List<SkuPrice> skuPrice = FastJsonUtil.toList(price.toString(), SkuPrice.class);
                                if (null != skuPrice && skuPrice.size() > 0) {
                                    gidtj.setPrice(skuPrice.get(0).getRetailPrice());
                                    gidtj.setBuyerPrice(skuPrice.get(0).getChannelPrice());
                                }

                                jsonList.add(gidtj);
                                System.out.println("sss");
                            }
                        }
                        dto.setGoodsInventoryDetail(JSONArray.fromObject(jsonList).toString());
                        System.out.println(skuList);
                    }
                }
                System.out.println(dto);
//                shoppingGoodsService.add(dto, ShiroUtils.getUserId());
            }
        }
        System.out.println(spuDetailList);
        return Ref.ok();
    }

    /**
     * 设置接口基础参数
     * @param params
     * @return
     */
    private static Map<String, String> setBaseParams(Map<String, String> params){
        params.put("appKey", appKey);
        params.put("currentTime", System.currentTimeMillis() + "");
        String sign = getSign(params, appSecret);
        params.put("sign", sign);
        System.out.println(sign);
        return params;
    }
    /**
     * 获取签名
     * @param params
     * @param appSecret
     * @return
     */
    public static String getSign(Map<String, String> params, String appSecret) {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (!entry.getKey().equals("sign")) {
                // 拼接参数值字符串并进行utf-8解码，防止中文乱码产生
                String value = "";
                try {
                    value = URLDecoder.decode(entry.getValue(), "UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (StringUtils.isEmpty(value)) {
                    continue;
                }
                params.put(entry.getKey(), value);
            }
        }
        // 将参数以参数名的字典升序排序
        Map<String, String> sortParams = new TreeMap<>(params);
        Set<Map.Entry<String, String>> entrys = sortParams.entrySet();
        // 遍历排序的字典,并拼接格式
        StringBuilder valueSb = new StringBuilder();
        for (Map.Entry<String, String> entry : entrys) {
            if (org.apache.commons.lang.StringUtils.isNotBlank(entry.getValue())) {
                valueSb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        valueSb.append(appSecret);
        String sign = valueSb.toString();
        try {
            sign = DigestUtils.md5Hex(sign.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return sign;
    }
}
